/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is ThumbsDown.
 *
 * The Initial Developer of the Original Code is
 * Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */


function ModePage() // extend WizardPage
{
    let depends = "selected linkUrls images target name";
    WizardPage.call(this, depends);
}

ModePage.prototype =
{
    get mode()      { return $("rgroup_mode"); },
    
    get filter() { return $("tbox_mode_filter"); },
    get tree()   { return $("tree_mode_scripts"); },
    
    get script() { return ((this.tree.currentIndex != -1) ? this.treeView.model[this.tree.currentIndex] : null); },
    
    
    onPageShow: function()
    {
        if (this.firstRun)
        {
            this.tree.view = this.treeView = new ScriptsTreeView(ScriptStore.getScripts());
            
            $("col_mode_label").style.width = _("css.modeLabelColumn.width");
        }
        
        if (this.dirty.selected || this.dirty.linkUrls || this.dirty.images)
        {
            this.entries =
                scriptWizard.getEntries({
                    thumbnail: model.selected,
                    linkUrl: model.linkUrls,
                    image: model.images,
                });
            
            this.mode.selectedIndex = -1;
            
            var rlbox = $("rlbox_mode");
            while (rlbox.itemCount > 0)
                rlbox.removeItemAt(0);
            
            for each (let entry in this.entries)
            {
                let rlitem = rlbox.appendItem(entry.linkUrl);
                rlitem.firstChild.crop = "none";
            }
        }
        
        if (this.dirty.linkUrls || (this.dirty.name && (this.mode.value != "modify")))
        {
            if (! model.name)
            {
                let linkUrls = [entry.linkUrl for each (entry in this.entries)];
                let linkUrlTokens = scriptWizard.getUrlTokens(linkUrls);
                model.name = scriptWizard.getName(linkUrlTokens);
            }
            
            this.filter.value = model.name;
            this.filter.doCommand();
        }
        
        if (this.mode.value != "modify")
            this.mode.value = "create";
        
        if (this.dirty.page)
            this._updateScript();
    },
    
    onModeSelect: function()
    {
        this._updateScript();
        wizard.updateWizardButtons();
    },
    
    onFilterCommand: function()
    {
        this._setFilter(this.filter.value);
    },
    
    onScriptSelect: function()
    {
        this.mode.value = "modify";
        
        this._updateScript();
        wizard.updateWizardButtons();
    },
    
    canAdvance: function()
    {
        switch (this.mode.value)
        {
            case "create":
                return true;
                
            case "modify":
                if (this.script && (this.script.thumbnailType == model.thumbnailType))
                {
                    switch (this.script.type)
                    {
                        case "direct":
                            return (model.target == "image");
                        case "regexp":
                        case "wrapped":
                            return (model.target == "page");
                    }
                }
                break;
        }
        return false;
    },
    
    _setFilter: function(text)
    {
        text = text.trim().toLocaleLowerCase();
        if (text.length == 0)
            this.treeView.filter = null;
        else
            this.treeView.filter = function(script) { return (script.nameLower.indexOf(text) != -1); }
    },
    
     _updateScript: function()
    {
        $("grid_mode_script").removeAttribute("type");
        
        let script = this.script;
        if ((this.mode.value == "modify") && script)
        {
            $("grid_mode_script").setAttribute("type", script.type);
            
            let thumbnailPattern = this.script.thumbnailPattern;
            let linkPattern = this.script.linkPattern;
            $("lbl_mode_script_thumbnailPattern").value = (thumbnailPattern ? thumbnailPattern.pattern : "");
            $("lbl_mode_script_linkPattern").value = (linkPattern ? linkPattern.pattern : "");
            
            switch (script.type)
            {
                case "regexp":
                    $("lbl_mode_script_regexp_source").value = _("type.regexp." + script.source);
                    $("lbl_mode_script_regexp_pattern").value = script.pattern.pattern;
                    $("lbl_mode_script_regexp_template").value = script.template;
                    break;
                    
                case "wrapped":
                    $("lbl_mode_script_wrapped_attrName").value = script.attrName;
                    $("lbl_mode_script_wrapped_attrValue").value = script.attrValue.pattern;
                    break;
            }
        }
    },
    
    onPageAdvanced: function()
    {
        model.mode = this.mode.value;
        
        switch (this.mode.value)
        {
            case "create":
                model.script = null;
                model.type = ((model.target == "image") ? "direct" : null);
                break;
            case "modify":
                model.script = this.script;
                model.type = this.script.type;
                break;
        }
        
        return true;
    }
}

extend(ModePage, WizardPage);

pages.mode = new ModePage();



// TODO: util.jsm has also FilteredTreeView but this is simpler
function ScriptsTreeView(model)
// extend TreeView
{
    this.model0 = model;
    this.model = model;
}

ScriptsTreeView.prototype =
{
    get filter() { return this._filter; },
    
    set filter(filter)
    {
        if (this.treeBoxObject)
        {
            this.treeBoxObject.beginUpdateBatch();
            this.treeBoxObject.rowCountChanged(0, -this.rowCount);
        }
        
        if (filter)
        {
            var n = this.model0.length;
            var index = 0;
            this.model = new Array(n);
            for (var i = 0; i < n; i++)
                if (filter(this.model0[i]))
                    this.model[index++] = this.model0[i];
            
            this.model.length = index;
        }
        else
        {
            this.model = this.model0.slice();
        }
                
        this._filter = filter;
        
        if (this.treeBoxObject)
            this.treeBoxObject.endUpdateBatch();
    },
    
    // nsITreeView
    getCellText: function(row, col)
    {
        var script = this.model[row];
        
        switch (col.id)
        {
            case "tcol_mode_script_name": return script.name;
            case "tcol_mode_script_thumbnailType": return _("thumbnailType." + script.thumbnailType);
            case "tcol_mode_script_type": return _("type." + script.type);
            default: return "";
        }
    },
    
    getCellProperties: function(row, col)
    {
        let script = this.model[row];
        let compatible = (script.thumbnailType == model.thumbnailType);
        
        if (compatible)
        {
            switch (script.type)
            {
                case "direct":
                    compatible = (model.target == "image");
                    break;
                case "regexp":
                case "wrapped":
                    compatible = (model.target == "page");
                    break;
                default:
                    compatible = false;
                    break;
            }
        }
        
        return (compatible ? "" : "incompatible");
    }
}

extend(ScriptsTreeView, TreeView);
